package nl.hva.three2learn.dao;

import java.util.List;

import nl.hva.three2learn.model.Course;
import nl.hva.three2learn.model.CoursePeriod;
import nl.hva.three2learn.model.Topic;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public final class CoursePeriodDaoImpl implements CoursePeriodDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public CoursePeriod findById(long coursePeriodId) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from CoursePeriod cp where cp.id = :id");
		q.setLong("id", coursePeriodId);
		
		Object result = q.uniqueResult();
		
		session.getTransaction().commit();
		
		if (result == null)
			return null;
		
		return (CoursePeriod) result;
	}	
	
	@Override
	public List<CoursePeriod> findAllCoursePeriods() { 
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from CoursePeriod");
		
		List<CoursePeriod> periods = q.list();
		
		session.getTransaction().commit();
		
		return periods;
	}
	
	@Override
	public List<CoursePeriod> findByCourse(Course course) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from CoursePeriod cp where cp.course = :course");
		q.setEntity("course", course);
		
		List<CoursePeriod> starts = q.list();
		session.getTransaction().commit();
		return starts;
	}
	
	@Override
	public void save(CoursePeriod period) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(period);
		session.getTransaction().commit();
	}
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
